package utils

import (
	"errors"
	"log"

	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"

	"main/src/models"
)

func ConnectDB(dsn string) *gorm.DB {
	var db *gorm.DB
	var err error
	if dsn == "inmemory" {
		log.Println("Using SQLite in-memory database")
		db, err = gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
		if err != nil {
			log.Fatalln("failed to connect to SQLite in-memory database")
		}
	} else {
		db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
		if err != nil {
			log.Fatalf("Failed to connect to database: %v", err)
		}
	}
	db.AutoMigrate(&models.User{})
	return db
}

func AddSuperAdmin(db *gorm.DB, username string, password string) {
	if db.Migrator().HasTable(&models.User{}) && !UserExists(db, username) {
		db.AutoMigrate(&models.User{})
		adminUser := models.User{
			Username: username,
			Password: password,
			Role:     "admin",
		}
		db.Create(&adminUser)
	}
}

func UserExists(db *gorm.DB, username string) bool {
	var foundUser models.User

	if err := db.Where("username = ?", username).First(&foundUser).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return false
		}
		// Handle other errors
		return false
	}

	return true
}

func GetUser(db *gorm.DB, user *models.User, foundUser *models.User) error {
	if err := db.Where("username = ?", user.Username).First(&foundUser).Error; err != nil {
		return err
	}

	return nil
}

func DeleteUser(db *gorm.DB, user *models.User) error {
	if err := db.Where("username = ?", user.Username).Delete(&user).Error; err != nil {
		return err
	}

	return nil
}

func AddUser(db *gorm.DB, user *models.User) error {
	if err := db.Create(&user).Error; err != nil {
		return err
	}

	return nil
}